#include <expat.h>
#include <stdio.h>
#define FILE_MAX_LENGTH 1024*4

int Depth;

static void XMLCALL
character(void *data,const XML_Char* s,int len){
	if(len==0 || (len==1 && s[0]=='\n'))return;
	char* buf=(char*)malloc(len+1);
	buf[len]='\0';
	memcpy(buf,s,len);
	printf("%s\n",buf);
}

static void XMLCALL
start(void *data,const char *el, const char **attr){
	int i;
	for(i=0;i<Depth;i++){
		printf("");
	}
	printf("%s",el);
	//print attributes;
	for(i=0;attr[i];i+=2){
		printf(" %s=%s",attr[i],attr[i+1]);
	}
	printf("\n");
	Depth++;
}

static void XMLCALL
end(void *data, const char *el){
	Depth--;
}

int main(){
	char* file="test.xml";
	FILE* fp=fopen(file,"r");
	char buffer[FILE_MAX_LENGTH];
	char c;
	int i=0;
	int depth;
	
	while( (c=fgetc(fp))!=EOF ){
		buffer[i]=c;
		i++;
	}
	buffer[i]='\0';
	printf("read:%s\n",buffer);
	
	XML_Parser p=XML_ParserCreate(NULL);
	if(!p){
		fprintf(stderr,"create xml parser error\n");
		exit(-1);
	}
//	XML_SetUserData(parser,&depth);
	XML_SetCharacterDataHandler(p,character);
	XML_SetElementHandler(p,start,end);
	if(XML_Parse(p,buffer,i,0)==XML_STATUS_ERROR){
		fprintf(stderr,"parse error at line %d:%s\n",
			XML_GetCurrentLineNumber(p),
			XML_ErrorString(XML_GetErrorCode(p)));
		exit(-1);	
	}
	return 0;
}